package com.lfg.leetcode.leetcode100;


import java.util.HashMap;
import java.util.Map;

public class No166fractionToDecimal {

    public static void main(String[] args) {
        String ret = fractionToDecimal(-50, 8);
        System.out.println(ret);
    }

    public static String fractionToDecimal(int numerator, int denominator) {
        StringBuilder sb = new StringBuilder();

        long numerator1 = numerator;
        long denominator1 = denominator;

        if (denominator1 == 0) {
            return sb.toString();
        }
        if (numerator1 == 0) {
            return sb.append('0').toString();
        }
        if (numerator1 < 0 ^ denominator1 < 0) {
            sb.append("-");
        }
        numerator1 = Math.abs(numerator1);
        denominator1 = Math.abs(denominator1);

        sb.append(numerator1 / denominator1);
        long remainder = numerator1 % denominator1;
        if (remainder == 0) {
            return sb.toString();
        }
        sb.append('.');
        Map<Long, Integer> data = new HashMap<>();
        int pos = sb.length();
        while (remainder != 0) {
            Integer index = data.get(remainder);
            if (null != index) {
                sb.insert(index, "(");
                sb.append(")");
                return sb.toString();
            }
            data.put(remainder, pos++);
            remainder *= 10;
            sb.append(remainder / denominator1);
            remainder = remainder % denominator1;
        }
        return sb.toString();
    }
}
